def session_exists(name):
    # lines of output containing 'name'
    import commands, os
    sessions = commands.getoutput("screen -ls")
    sessions_split = sessions.split('\n')
    sessions_split_with_name = [s for s in sessions_split if name in s]
    sessions_split_with_name = [s.split('\t') for s in sessions_split_with_name]
    sessions_names = []
    for s in sessions_split_with_name:
        for c in s:
            sessions_names += [c]
    session_names_split = [s.split('.') for s in sessions_names ]
    if len([n[1]==name for n in session_names_split if len(n) > 1])==0:
        return False
    else:
        return True

def run_cmds(fileformat, schemaname, dbname, name1, name2):
    import os, time
    # Create session only if a session of that name does not already exist
    if not session_exists(name1):
        os.system("screen -dmS %s"%name1)
    if not session_exists(name2):
        os.system("screen -dmS %s"%name2)

    #screen -S foo -X emacs -nw foo
    #screen -S meminfo -X eval 'stuff emacs -nw somefile\015'
    #c2 = "screen -S meminfo -X eval 'stuff \"ls -la^M\"'"
    #cmd = "ls -la"
    #c2 = "screen -S meminfo -X eval 'stuff \"" + c2 + "^M\"'"

    filename = "%s.%s.%s"%(dbname, schemaname, fileformat)
    if os.path.exists(filename) and os.path.getsize(filename) > 0:
        print "%s already exists, exiting"%filename
        sys.exit(1)

    c1 = "python make_output.py %s %s %s"%(fileformat, schemaname, dbname)
    c2 = "python meminfo.py %s"%("meminfo" + "_" + fileformat + "_" + schemaname + "_" + dbname + ".csv")
    os.system("screen -S %s -X screen %s"%(name1, c1))
    time.sleep(10)
    os.system("screen -S %s -X screen %s"%(name2, c2))

import sys, traceback
from optparse import OptionParser
usage = "usage is of the form '%prog -c fileformat schemaname dbname'\n" \
      + "choices for fileformat are %s"%(', '.join(["map", "ped", "tfam", "tped", "pheno"]))
parser = OptionParser(usage=usage)
parser.add_option("-c", "--map-col", action="store_true", dest="mapcol", help="add column to map file")
(options, args) = parser.parse_args()
if len(args) < 3:
    print "incorrect number of arguments"
    parser.print_help()
    sys.exit()

fileformat = args[0]
schemaname = args[1]
dbname = args[2]
name1="%s_%s_%s"%(fileformat, schemaname, dbname)
name2="meminfo_%s_%s_%s"%(fileformat, schemaname, dbname)
run_cmds(fileformat, schemaname, dbname, name1, name2)
